import os
import re

def main():
    # 配置区域 - 可据实际情况修改
    TARGET_FOLDER = "./student_files"  # 存放学生文件的文件夹
    STANDARD_FORMAT = "{class}-{id}-{name}{ext}"  # 规范格式
    STUDENTS = {  # 学生信息：姓名 -> (学号, 班级)
        "小赵": ("24403000601", "网工2403"),
        "小钱": ("24403000602", "网工2403"),
        "小孙": ("24403000603", "网工2403"),
        "小李": ("24403000604", "网工2403"),
        "小高": ("24403000605", "网工2403")
    }
    SUPPORTED_EXTENSIONS = ('.zip', '.rar', '.7z', '.tar', '.gz')  # 支持的压缩文件格式

    # 创建学号到学生信息的映射
    id_mapping = {info[0]: (name, info[1]) for name, info in STUDENTS.items()}
    
    # 确保目标文件夹存在
    if not os.path.exists(TARGET_FOLDER):
        os.makedirs(TARGET_FOLDER)
        print(f"已创建文件夹: {TARGET_FOLDER}")
        print("请将需要重命名的文件放入该文件夹后重新运行程序")
        return

    # 处理文件夹中的所有文件
    unrecognized = []
    
    for filename in os.listdir(TARGET_FOLDER):
        file_path = os.path.join(TARGET_FOLDER, filename)
        
        # 只处理文件，跳过文件夹
        if not os.path.isfile(file_path):
            continue
            
        # 分离文件名和扩展名
        name_part, ext = os.path.splitext(filename)
        
        # 只处理支持的文件类型
        if ext.lower() not in SUPPORTED_EXTENSIONS:
            continue
        
        # 尝试识别学生信息
        student_name = None
        student_id = None
        student_class = None
        
        # 1. 尝试通过姓名识别
        for name in STUDENTS:
            if name in name_part:
                student_name = name
                student_id, student_class = STUDENTS[name]
                break
        
        # 2. 如果姓名识别失败，尝试通过学号识别
        if not student_name:
            # 查找10-12位数字作为学号
            match = re.search(r'\b\d{10,12}\b', name_part)
            if match and match.group() in id_mapping:
                student_id = match.group()
                student_name, student_class = id_mapping[student_id]
        
        # 执行重命名
        if student_name and student_id and student_class:
            # 生成新文件名
            new_filename = STANDARD_FORMAT.format(
                class=student_class,
                id=student_id,
                name=student_name,
                ext=ext
            )
            new_path = os.path.join(TARGET_FOLDER, new_filename)
            
            # 处理重名情况
            counter = 1
            while os.path.exists(new_path):
                new_filename = f"{student_class}-{student_id}-{student_name}_{counter}{ext}"
                new_path = os.path.join(TARGET_FOLDER, new_filename)
                counter += 1
            
            # 执行重命名
            os.rename(file_path, new_path)
            print(f"已重命名: {filename} → {new_filename}")
        else:
            unrecognized.append(filename)
    
    # 显示无法识别的文件
    if unrecognized:
        print("\n以下文件无法识别，请手动处理:")
        for file in unrecognized:
            print(f"- {file}")
    
    print("\n处理完成！")

if __name__ == "__main__":
    main()
